<template>
  <div>
    <el-button @click="dialogVisible = true">打开Dialog</el-button>
    <el-dialog title="提示" :visible.sync="dialogVisible">
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-form ref="form" :model="form" label-width="100px">
      <el-form-item label="聊天信息">
        <el-input type="textarea" v-model="form.desc"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
    <div class="chat-info" ref="chatRoom">
      <p v-for="(item, index) in msgs" :key="index">{{ item }}</p>
    </div>
  </div>
</template>
<script>
export default {
  name: 'TestSocket',
  data () {
    return {
      socket: '',
      dialogVisible: false,
      form: {
        desc: ''
      },
      msgs: []
    }
  },
  created () {
    this.initSocket()
  },
  methods: {
    initSocket () {
      // this.socket = new WebSocket('ws://127.0.0.1:8080/chat')
      this.socket = new WebSocket('wss://miaochunxu.com/api/chat')
      // 连接错误
      this.socket.onerror = this.error

      // 连接成功
      this.socket.onopen = this.open

      // 收到消息的回调
      this.socket.onmessage = this.onSocketMessage

      // 连接关闭的回调
      this.socket.onclose = this.close

      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    onSubmit () {
      console.log('submit')
      let desc = this.form.desc
      this.socket.send(desc)
      this.form.desc = ''
    },

    open () {
      console.log('socket连接成功')
      this.msgs.push('socket 连接成功')
    },
    error (event) {
      console.log('连接错误')
      console.log(event)
    },
    onSocketMessage (event) {
      console.log(event)
      console.log('接收到的消息是 ' + event.data)
      this.msgs.push(event.data)
    },
    close (event) {
      console.log('socket已经关闭')
      console.log(event)
      this.msgs.push('socket 已经关闭')
    },
    onbeforeunload () {
      this.closeWebSocket()
    },
    closeWebSocket () {
      this.close()
    }
  },
  beforeDestroy () {
    this.onbeforeunload()
  },
  destroyed () {
    this.onbeforeunload()
  }
}
</script>
<style scoped>
</style>
